import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Deliverycollaboration {
  private static Account account = new Account();

  public static void main(String[] args) {
    // Create a thread pool with two threads
    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.execute(new DepositTask());
    executor.execute(new WithdrawTask());
    executor.shutdown();
  }

  public static class DepositTask implements Runnable {
    public void run() {
      try {
        while (true) {
          account.deposit((int)(Math.random() * 100) + 1);
          Thread.sleep(300);

        }
      }
      catch (InterruptedException ex) {
        ex.printStackTrace();
      }
    }
  }

  public static class WithdrawTask implements Runnable {
    public void run() {
      while (true) {
        account.withdraw((int)(Math.random() * 10) + 1);
        try {
          Thread.sleep(300);
        } catch (InterruptedException e) {
          throw new RuntimeException(e);
        }
      }
    }
  }

  // An inner class for account
  private static class Account {
    // Create a new lock
    private static Lock lock = new ReentrantLock();

    // Create a condition
    private static Condition newDeposit = lock.newCondition();

    private int balance = 0;

    public int getBalance() {
      return balance;
    }

    public void withdraw(int amount) {

      lock.lock();
      try {
        while (balance < amount) {
          System.out.println("要取出的快递不足，等待快递员存入快递...");
          newDeposit.await();
        }
        balance -= amount;
        System.out.println("用户取出了" + amount + "个包裹,包裹箱还剩下" +
                getBalance() + "个包裹");
        newDeposit.signalAll();
      }
      catch (InterruptedException ex) {
        ex.printStackTrace();
      }
      finally {
        lock.unlock();
      }
    }
    public void deposit(int amount) {
      lock.lock();
      try {
        balance += amount;
        System.out.println("快递员存入了" + amount + "个包裹，现包裹箱里还剩" +
                getBalance() + "个包裹");
        newDeposit.signalAll();
        while (balance>=10){
          newDeposit.await();
        }

      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      } finally {
        lock.unlock();
      }
    }
  }
}
